const _ = require("lodash");
const fs = require("fs");

function capitalize(name = "") {
  return name
    .split("-")
    .map((n) => _.capitalize(n))
    .join("");
}

/**
 * @callback FilesCallbackFn
 * @param {string} folder
 * @param {string} file
 * @returns {void}
 */

/**
 * @typedef {object} AutoExportParams
 * @property {string} libName - pkg的短名
 * @property {string} [styleName=style] - 样式文件夹的名称，默认为`style`
 * @property {string} excludeTemplate - 入口文件额外的字符串模板
 * @property {string[]} [lowPriorityFiles=[]] - 优先权低的的组件名列表
 * @property {string[]} [excludeFiles=[]] - 要排除导出的组件名列表
 * @property {?FilesCallbackFn} callbackfn - 要排除导出的组件名列表
 */

/**
 * 一个简单的nodejs脚本，用于处理组件库入口文件的export自动生成。
 *
 * @param {AutoExportParams} params
 */
module.exports = function (params) {
  const {
    excludeFiles = [],
    lowPriorityFiles = [],
    excludeTemplate = "",
    styleName = "style",
    libName = "",
    callbackfn,
  } = params;
  if (!libName) throw Error(`libName cannot be empty.`);
  const tempFiles = fs.readdirSync("./src");
  const arrFiles = tempFiles.filter((name) => !name.includes("."));

  /** @type {string[]} */
  const data = [];
  /** @type {string[]} */
  const stylesData = [];
  /** @type {string[]} */
  const stylesInxData = [];

  arrFiles.forEach((folder) => {
    const files = fs.readdirSync(`./src/${folder}`);
    files
      .filter((file) => !excludeFiles.includes(file))
      .filter((file) => fs.existsSync(`./src/${folder}/${file}/style`))
      .forEach((file) => {
        data.push(
          `export { default as ${capitalize(file)} } from './${folder}/${file}';
export * from './${folder}/${file}';`
        );
        if (lowPriorityFiles.includes(file)) {
          stylesData.unshift(`@import '../${file}/style/index.less';`);
          stylesInxData.unshift(`import '../${file}/style';`);
        } else {
          stylesData.push(`@import '../${file}/style/index.less';`);
          stylesInxData.push(`import '../${file}/style';`);
        }

        callbackfn?.(folder, file);
      });
  });

  fs.writeFileSync("./src/index.ts", data.join("\n") + excludeTemplate);
  fs.writeFileSync(
    `./src/${libName}/${styleName}/index.ts`,
    stylesInxData.join("\n") + "\n"
  );
  fs.writeFileSync(
    `./src/${libName}/${styleName}/index.less`,
    stylesData.join("\n") + "\n"
  );
};
